package com.qf.controller;

import com.qf.constant.LiuBackConstant;
import com.qf.entity.TUser;
import com.qf.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * @author LiuLiang
 * @Date 2020/3/11
 */

@Controller
//@RequestMapping("/back")
public class LoginController {
    @Autowired
    private ILoginService loginService;

    @Autowired
    private RedisTemplate<Object,Object> template;

    @RequestMapping("/login")
    public String login(String username, String password, HttpServletResponse resp, @CookieValue(value = LiuBackConstant.BACK_USER_LOGIN,required = false)String userCookie){

        TUser tUser = loginService.checkLogin(username, password);
        if (tUser == null){

            try {
                resp.setContentType("text/html; charset=utf-8");
                PrintWriter out = resp.getWriter();
                out.print("<script>alert('用户名或密码错误');</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "back_login";
        }

        if(userCookie == null){
            userCookie = UUID.randomUUID().toString().replaceAll("-","");
        }
        template.opsForValue().set(LiuBackConstant.BACK_USER_LOGIN+userCookie,tUser);

        Cookie cookie = new Cookie(LiuBackConstant.BACK_USER_LOGIN,userCookie);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*15);
        resp.addCookie(cookie);
        return "home";
    }

    @RequestMapping("index")
    public String index(){
        return "back_login";
    }
}
